package org.jeecg.modules.wms.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.wms.entity.WmsPurchaseArrivalInspection;
import org.jeecg.modules.wms.entity.WmsPurchaseOrder;
import org.jeecg.modules.wms.entity.WmsPurchaseReturnExchange;
import org.jeecg.modules.wms.mapper.WmsPurchaseReturnExchangeMapper;
import org.jeecg.modules.wms.service.IWmsPurchaseArrivalInspectionService;
import org.jeecg.modules.wms.service.IWmsPurchaseOrderService;
import org.jeecg.modules.wms.service.IWmsPurchaseReturnExchangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 采购退货换货记录表
 * @Author: jeecg-boot
 * @Date: 2023-08-10
 * @Version: V1.0
 */
@Service
@Slf4j
public class WmsPurchaseReturnExchangeServiceImpl extends ServiceImpl<WmsPurchaseReturnExchangeMapper, WmsPurchaseReturnExchange> implements IWmsPurchaseReturnExchangeService {
    @Autowired
    private WmsPurchaseReturnExchangeMapper wmsPurchaseReturnExchangeMapper;
    
    @Autowired
    private IWmsPurchaseOrderService wmsPurchaseOrderService;
    
    @Autowired
    private IWmsPurchaseArrivalInspectionService wmsPurchaseArrivalInspectionService;
    
    @Override
    public List<WmsPurchaseReturnExchange> getByPurchaseOrderId(String purchaseOrderId) {
        return wmsPurchaseReturnExchangeMapper.getByPurchaseOrderId(purchaseOrderId);
    }
    
    @Override
    public List<WmsPurchaseReturnExchange> getByInspectionId(String inspectionId) {
        return wmsPurchaseReturnExchangeMapper.getByInspectionId(inspectionId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> createReturnRecord(Map<String, Object> params, String username) {
        try {
            // 参数验证
            String purchaseOrderId = (String) params.get("purchaseOrderId");
            String inspectionId = (String) params.get("inspectionId");
            String quantity = params.get("quantity").toString();
            String reason = (String) params.get("reason");
            String evidence = (String) params.get("evidence");
            String returnExchangeNo = (String) params.get("returnExchangeNo");
            BigDecimal unitPrice = new BigDecimal(params.get("unitPrice").toString());
            BigDecimal totalAmount = new BigDecimal(params.get("totalAmount").toString());
            
            if (StringUtils.isBlank(purchaseOrderId)) {
                return Result.error("采购单ID不能为空");
            }
            
            if (StringUtils.isBlank(inspectionId)) {
                return Result.error("质检记录ID不能为空");
            }
            
            if (StringUtils.isBlank(quantity) || new BigDecimal(quantity).compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("退货数量必须大于0");
            }
            
            if (StringUtils.isBlank(reason)) {
                return Result.error("退货原因不能为空");
            }
            
            // 查询质检记录
            WmsPurchaseArrivalInspection inspection = wmsPurchaseArrivalInspectionService.getById(inspectionId);
            if (inspection == null) {
                return Result.error("质检记录不存在");
            }
            
            // 验证数量
            BigDecimal returnQuantity = new BigDecimal(quantity);
            if (returnQuantity.compareTo(inspection.getUnqualifiedQuantity()) > 0) {
                return Result.error("退货数量不能超过不合格数量");
            }
            
            // 创建退货记录
            WmsPurchaseReturnExchange returnRecord = new WmsPurchaseReturnExchange();
            returnRecord.setPurchaseOrderId(purchaseOrderId);
            returnRecord.setPurchaseOrderNo((String) params.get("purchaseOrderNo"));
            returnRecord.setInspectionId(inspectionId);
            returnRecord.setMaterialId((String) params.get("materialId"));
            returnRecord.setMaterialCode((String) params.get("materialCode"));
            returnRecord.setMaterialName((String) params.get("materialName"));
            returnRecord.setMaterialType((String) params.get("materialType"));
            returnRecord.setSpecification((String) params.get("specification"));
            returnRecord.setQuantity(returnQuantity);
            returnRecord.setUnit((String) params.get("unit"));
            returnRecord.setUnitPrice(unitPrice);
            returnRecord.setTotalAmount(totalAmount);
            returnRecord.setReturnExchangeNo(returnExchangeNo);
            returnRecord.setType(1); // 1-退货
            returnRecord.setStatus(0); // 0-待处理
            returnRecord.setReason(reason);
            returnRecord.setEvidence(evidence);
            returnRecord.setSupplierId((String) params.get("supplierId"));
            returnRecord.setSupplierName((String) params.get("supplierName"));
            returnRecord.setCreateBy(username);
            returnRecord.setCreateTime(new Date());
            
            // 保存记录
            this.save(returnRecord);
            
            // 更新质检记录的处理状态
            inspection.setStatus(1); // 1-已处理
            inspection.setUpdateBy(username);
            inspection.setUpdateTime(new Date());
            wmsPurchaseArrivalInspectionService.updateById(inspection);
            
            // 更新采购单的退换货状态
            WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getById(purchaseOrderId);
            if (purchaseOrder != null) {
                purchaseOrder.setReturnExchangeStatus(2); // 2-退货
                purchaseOrder.setUpdateBy(username);
                purchaseOrder.setUpdateTime(new Date());
                wmsPurchaseOrderService.updateById(purchaseOrder);
            }
            
            return Result.ok("退货记录创建成功");
        } catch (Exception e) {
            log.error("创建退货记录失败", e);
            return Result.error("创建退货记录失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> createExchangeRecord(Map<String, Object> params, String username) {
        try {
            // 参数验证
            String purchaseOrderId = (String) params.get("purchaseOrderId");
            String inspectionId = (String) params.get("inspectionId");
            String quantity = params.get("quantity").toString();
            String reason = (String) params.get("reason");
            String evidence = (String) params.get("evidence");
            String returnExchangeNo = (String) params.get("returnExchangeNo");
            BigDecimal unitPrice = new BigDecimal(params.get("unitPrice").toString());
            BigDecimal totalAmount = new BigDecimal(params.get("totalAmount").toString());
            
            if (StringUtils.isBlank(purchaseOrderId)) {
                return Result.error("采购单ID不能为空");
            }
            
            if (StringUtils.isBlank(inspectionId)) {
                return Result.error("质检记录ID不能为空");
            }
            
            if (StringUtils.isBlank(quantity) || new BigDecimal(quantity).compareTo(BigDecimal.ZERO) <= 0) {
                return Result.error("换货数量必须大于0");
            }
            
            if (StringUtils.isBlank(reason)) {
                return Result.error("换货原因不能为空");
            }
            
            // 查询质检记录
            WmsPurchaseArrivalInspection inspection = wmsPurchaseArrivalInspectionService.getById(inspectionId);
            if (inspection == null) {
                return Result.error("质检记录不存在");
            }
            
            // 验证数量
            BigDecimal exchangeQuantity = new BigDecimal(quantity);
            if (exchangeQuantity.compareTo(inspection.getUnqualifiedQuantity()) > 0) {
                return Result.error("换货数量不能超过不合格数量");
            }
            
            // 创建换货记录
            WmsPurchaseReturnExchange exchangeRecord = new WmsPurchaseReturnExchange();
            exchangeRecord.setPurchaseOrderId(purchaseOrderId);
            exchangeRecord.setPurchaseOrderNo((String) params.get("purchaseOrderNo"));
            exchangeRecord.setInspectionId(inspectionId);
            exchangeRecord.setMaterialId((String) params.get("materialId"));
            exchangeRecord.setMaterialCode((String) params.get("materialCode"));
            exchangeRecord.setMaterialName((String) params.get("materialName"));
            exchangeRecord.setMaterialType((String) params.get("materialType"));
            exchangeRecord.setSpecification((String) params.get("specification"));
            exchangeRecord.setQuantity(exchangeQuantity);
            exchangeRecord.setUnit((String) params.get("unit"));
            exchangeRecord.setUnitPrice(unitPrice);
            exchangeRecord.setTotalAmount(totalAmount);
            exchangeRecord.setReturnExchangeNo(returnExchangeNo);
            exchangeRecord.setType(2); // 2-换货
            exchangeRecord.setStatus(0); // 0-待处理
            exchangeRecord.setReason(reason);
            exchangeRecord.setEvidence(evidence);
            exchangeRecord.setSupplierId((String) params.get("supplierId"));
            exchangeRecord.setSupplierName((String) params.get("supplierName"));
            exchangeRecord.setCreateBy(username);
            exchangeRecord.setCreateTime(new Date());
            
            // 保存记录
            this.save(exchangeRecord);
            
            // 更新质检记录的处理状态
            inspection.setStatus(1); // 1-已处理
            inspection.setUpdateBy(username);
            inspection.setUpdateTime(new Date());
            wmsPurchaseArrivalInspectionService.updateById(inspection);
            
            // 更新采购单的退换货状态
            WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getById(purchaseOrderId);
            if (purchaseOrder != null) {
                purchaseOrder.setReturnExchangeStatus(3); // 3-换货
                purchaseOrder.setUpdateBy(username);
                purchaseOrder.setUpdateTime(new Date());
                wmsPurchaseOrderService.updateById(purchaseOrder);
            }
            
            return Result.ok("换货记录创建成功");
        } catch (Exception e) {
            log.error("创建换货记录失败", e);
            return Result.error("创建换货记录失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> processRecord(String id, Integer status, String remark, String username) {
        try {
            if (StringUtils.isBlank(id)) {
                return Result.error("记录ID不能为空");
            }
            
            if (status == null || (status != 1 && status != 2)) {
                return Result.error("状态值无效");
            }
            
            // 查询记录
            WmsPurchaseReturnExchange record = this.getById(id);
            if (record == null) {
                return Result.error("记录不存在");
            }
            
            // 验证状态
            if (record.getStatus() != 0) {
                return Result.error("只有待处理的记录才能进行处理");
            }
            
            // 更新状态
            record.setStatus(status);
            record.setRemark(remark);
            record.setProcessBy(username);
            record.setProcessTime(new Date());
            record.setUpdateBy(username);
            record.setUpdateTime(new Date());
            
            this.updateById(record);
            
            return Result.ok("处理成功");
        } catch (Exception e) {
            log.error("处理退货/换货记录失败", e);
            return Result.error("处理失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> cancelRecord(String id, String remark, String username) {
        try {
            if (StringUtils.isBlank(id)) {
                return Result.error("记录ID不能为空");
            }
            
            // 查询记录
            WmsPurchaseReturnExchange record = this.getById(id);
            if (record == null) {
                return Result.error("记录不存在");
            }
            
            // 验证状态
            if (record.getStatus() == 2 || record.getStatus() == 3) {
                return Result.error("已完成或已取消的记录不能再次取消");
            }
            
            // 更新状态
            record.setStatus(3); // 3-已取消
            record.setRemark(remark);
            record.setUpdateBy(username);
            record.setUpdateTime(new Date());
            
            this.updateById(record);
            
            return Result.ok("取消成功");
        } catch (Exception e) {
            log.error("取消退货/换货记录失败", e);
            return Result.error("取消失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchCreateReturnRecord(Map<String, Object> params, String username) {
        try {
            // 参数验证
            String purchaseOrderId = (String) params.get("purchaseOrderId");
            String purchaseOrderNo = (String) params.get("purchaseOrderNo");
            String reason = (String) params.get("reason");
            String evidence = (String) params.get("evidence");
            String returnExchangeNo = (String) params.get("returnExchangeNo");
            List<Map<String, Object>> items = (List<Map<String, Object>>) params.get("items");
            
            if (StringUtils.isBlank(purchaseOrderId)) {
                return Result.error("采购单ID不能为空");
            }
            
            if (StringUtils.isBlank(purchaseOrderNo)) {
                return Result.error("采购单号不能为空");
            }
            
            if (StringUtils.isBlank(reason)) {
                return Result.error("退货原因不能为空");
            }
            
            if (items == null || items.isEmpty()) {
                return Result.error("退货物料不能为空");
            }
            
            // 批量创建退货记录
            List<WmsPurchaseReturnExchange> returnRecords = new ArrayList<>();
            List<String> inspectionIds = new ArrayList<>();
            
            for (Map<String, Object> item : items) {
                String inspectionId = (String) item.get("inspectionId");
                String materialId = (String) item.get("materialId");
                String materialCode = (String) item.get("materialCode");
                String materialName = (String) item.get("materialName");
                String materialType = (String) item.get("materialType");
                String specification = (String) item.get("specification");
                String unit = (String) item.get("unit");
                BigDecimal quantity = new BigDecimal(item.get("quantity").toString());
                BigDecimal unitPrice = new BigDecimal(item.get("unitPrice").toString());
                BigDecimal totalAmount = new BigDecimal(item.get("totalAmount").toString());
                String supplierId = (String) item.get("supplierId");
                String supplierName = (String) item.get("supplierName");
                
                // 查询质检记录
                WmsPurchaseArrivalInspection inspection = wmsPurchaseArrivalInspectionService.getById(inspectionId);
                if (inspection == null) {
                    return Result.error("质检记录不存在: " + materialCode);
                }
                
                // 验证数量
                if (quantity.compareTo(inspection.getUnqualifiedQuantity()) > 0) {
                    return Result.error("退货数量不能超过不合格数量: " + materialCode);
                }
                
                // 创建退货记录
                WmsPurchaseReturnExchange returnRecord = new WmsPurchaseReturnExchange();
                returnRecord.setPurchaseOrderId(purchaseOrderId);
                returnRecord.setPurchaseOrderNo(purchaseOrderNo);
                returnRecord.setInspectionId(inspectionId);
                returnRecord.setMaterialId(materialId);
                returnRecord.setMaterialCode(materialCode);
                returnRecord.setMaterialName(materialName);
                returnRecord.setMaterialType(materialType);
                returnRecord.setSpecification(specification);
                returnRecord.setQuantity(quantity);
                returnRecord.setUnit(unit);
                returnRecord.setUnitPrice(unitPrice);
                returnRecord.setTotalAmount(totalAmount);
                returnRecord.setReturnExchangeNo(returnExchangeNo);
                returnRecord.setType(1); // 1-退货
                returnRecord.setStatus(0); // 0-待处理
                returnRecord.setReason(reason);
                returnRecord.setEvidence(evidence);
                returnRecord.setSupplierId(supplierId);
                returnRecord.setSupplierName(supplierName);
                returnRecord.setCreateBy(username);
                returnRecord.setCreateTime(new Date());
                
                returnRecords.add(returnRecord);
                inspectionIds.add(inspectionId);
            }
            
            // 保存记录
            this.saveBatch(returnRecords);
            
            // 更新质检记录的处理状态
            for (String inspectionId : inspectionIds) {
                WmsPurchaseArrivalInspection inspection = wmsPurchaseArrivalInspectionService.getById(inspectionId);
                if (inspection != null) {
                    inspection.setStatus(1); // 1-已处理
                    inspection.setUpdateBy(username);
                    inspection.setUpdateTime(new Date());
                    wmsPurchaseArrivalInspectionService.updateById(inspection);
                }
            }
            
            // 更新采购单的退换货状态
            WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getById(purchaseOrderId);
            if (purchaseOrder != null) {
                purchaseOrder.setReturnExchangeStatus(2); // 2-退货
                purchaseOrder.setUpdateBy(username);
                purchaseOrder.setUpdateTime(new Date());
                wmsPurchaseOrderService.updateById(purchaseOrder);
            }
            
            return Result.ok("批量退货记录创建成功");
        } catch (Exception e) {
            log.error("批量创建退货记录失败", e);
            return Result.error("批量创建退货记录失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchCreateExchangeRecord(Map<String, Object> params, String username) {
        try {
            // 参数验证
            String purchaseOrderId = (String) params.get("purchaseOrderId");
            String purchaseOrderNo = (String) params.get("purchaseOrderNo");
            String reason = (String) params.get("reason");
            String evidence = (String) params.get("evidence");
            String returnExchangeNo = (String) params.get("returnExchangeNo");
            List<Map<String, Object>> items = (List<Map<String, Object>>) params.get("items");
            
            if (StringUtils.isBlank(purchaseOrderId)) {
                return Result.error("采购单ID不能为空");
            }
            
            if (StringUtils.isBlank(purchaseOrderNo)) {
                return Result.error("采购单号不能为空");
            }
            
            if (StringUtils.isBlank(reason)) {
                return Result.error("换货原因不能为空");
            }
            
            if (items == null || items.isEmpty()) {
                return Result.error("换货物料不能为空");
            }
            
            // 批量创建换货记录
            List<WmsPurchaseReturnExchange> exchangeRecords = new ArrayList<>();
            List<String> inspectionIds = new ArrayList<>();
            
            for (Map<String, Object> item : items) {
                String inspectionId = (String) item.get("inspectionId");
                String materialId = (String) item.get("materialId");
                String materialCode = (String) item.get("materialCode");
                String materialName = (String) item.get("materialName");
                String materialType = (String) item.get("materialType");
                String specification = (String) item.get("specification");
                String unit = (String) item.get("unit");
                BigDecimal quantity = new BigDecimal(item.get("quantity").toString());
                BigDecimal unitPrice = new BigDecimal(item.get("unitPrice").toString());
                BigDecimal totalAmount = new BigDecimal(item.get("totalAmount").toString());
                String supplierId = (String) item.get("supplierId");
                String supplierName = (String) item.get("supplierName");
                
                // 查询质检记录
                WmsPurchaseArrivalInspection inspection = wmsPurchaseArrivalInspectionService.getById(inspectionId);
                if (inspection == null) {
                    return Result.error("质检记录不存在: " + materialCode);
                }
                
                // 验证数量
                if (quantity.compareTo(inspection.getUnqualifiedQuantity()) > 0) {
                    return Result.error("换货数量不能超过不合格数量: " + materialCode);
                }
                
                // 创建换货记录
                WmsPurchaseReturnExchange exchangeRecord = new WmsPurchaseReturnExchange();
                exchangeRecord.setPurchaseOrderId(purchaseOrderId);
                exchangeRecord.setPurchaseOrderNo(purchaseOrderNo);
                exchangeRecord.setInspectionId(inspectionId);
                exchangeRecord.setMaterialId(materialId);
                exchangeRecord.setMaterialCode(materialCode);
                exchangeRecord.setMaterialName(materialName);
                exchangeRecord.setMaterialType(materialType);
                exchangeRecord.setSpecification(specification);
                exchangeRecord.setQuantity(quantity);
                exchangeRecord.setUnit(unit);
                exchangeRecord.setUnitPrice(unitPrice);
                exchangeRecord.setTotalAmount(totalAmount);
                exchangeRecord.setReturnExchangeNo(returnExchangeNo);
                exchangeRecord.setType(2); // 2-换货
                exchangeRecord.setStatus(0); // 0-待处理
                exchangeRecord.setReason(reason);
                exchangeRecord.setEvidence(evidence);
                exchangeRecord.setSupplierId(supplierId);
                exchangeRecord.setSupplierName(supplierName);
                exchangeRecord.setCreateBy(username);
                exchangeRecord.setCreateTime(new Date());
                
                exchangeRecords.add(exchangeRecord);
                inspectionIds.add(inspectionId);
            }
            
            // 保存记录
            this.saveBatch(exchangeRecords);
            
            // 更新质检记录的处理状态
            for (String inspectionId : inspectionIds) {
                WmsPurchaseArrivalInspection inspection = wmsPurchaseArrivalInspectionService.getById(inspectionId);
                if (inspection != null) {
                    inspection.setStatus(1); // 1-已处理
                    inspection.setUpdateBy(username);
                    inspection.setUpdateTime(new Date());
                    wmsPurchaseArrivalInspectionService.updateById(inspection);
                }
            }
            
            // 更新采购单的退换货状态
            WmsPurchaseOrder purchaseOrder = wmsPurchaseOrderService.getById(purchaseOrderId);
            if (purchaseOrder != null) {
                purchaseOrder.setReturnExchangeStatus(3); // 3-换货
                purchaseOrder.setUpdateBy(username);
                purchaseOrder.setUpdateTime(new Date());
                wmsPurchaseOrderService.updateById(purchaseOrder);
            }
            
            return Result.ok("批量换货记录创建成功");
        } catch (Exception e) {
            log.error("批量创建换货记录失败", e);
            return Result.error("批量创建换货记录失败: " + e.getMessage());
        }
    }
} 